// client.go
package main

import (
	"encoding/binary"
	"flag"
	"fmt"
	"github.com/sirupsen/logrus"
	"net"
	"time"
)

func main() {
	// 解析命令行参数
	port := flag.Int("port", 8080, "TCP server port")
	host := flag.String("host", "localhost", "Server host address")
	flag.Parse()

	// 初始化 Logrus
	log := logrus.New()
	log.SetFormatter(&logrus.TextFormatter{
		FullTimestamp: true,
	})
	log.SetLevel(logrus.InfoLevel)

	// 连接到服务端
	addr := fmt.Sprintf("%s:%d", *host, *port)
	conn, err := net.Dial("tcp", addr)
	if err != nil {
		log.Fatalf("Failed to connect to server %s: %v", addr, err)
	}
	defer conn.Close()
	log.Infof("Connected to server %s", addr)
	var idx uint64 = 0

	for {
		// 发送消息
		message := fmt.Sprintf("Hello, TCP Server! %d", idx)
		msgLen := uint32(len(message))

		// 构造消息：4 字节长度 + 消息内容
		buf := make([]byte, 4+len(message))
		binary.BigEndian.PutUint32(buf[0:4], msgLen)
		copy(buf[4:], message)

		// 发送消息
		_, err = conn.Write(buf)
		if err != nil {
			log.Errorf("Failed to send message: %v", err)
			return
		}
		log.Infof("Sent message: %s", message)

		// 接收响应
		lengthBuf := make([]byte, 4)
		_, err = conn.Read(lengthBuf)
		if err != nil {
			log.Errorf("Failed to read response length: %v", err)
			return
		}

		// 解析响应长度
		respLen := binary.BigEndian.Uint32(lengthBuf)
		response := make([]byte, respLen)
		_, err = conn.Read(response)
		if err != nil {
			log.Errorf("Failed to read response: %v", err)
			return
		}
		log.Infof("Received response: %s", string(response))
		idx++
		time.Sleep(500 * time.Millisecond)
	}

}
